import axios from 'axios'
// import qs from 'qs'
import { ElMessage } from 'element-plus'

// 设置拦截器
axios.interceptors.request.use(
    config => {
        // 在发送请求前进行的操作
        const token = window.sessionStorage.getItem('token');
        config.headers['Authorization'] = token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// axios响应式拦截器
axios.interceptors.response.use(config => {
    if (config.data) {
        if (config.data.code == '200') {
            return config.data
        } else {
            return config
        }
    } else {
        if (config.data.code) {
            ElMessage({
                type: 'warning',
                message: config.data.msg
            })
        }
    }
}, e => {
    // 统一错误提示
    ElMessage({
        type: 'warning',
        message: e.response.data.message
    })
    return Promise.reject(e)
})

const post = (url, data) => {
    return axios({
        method: 'post',
        url,
        data: data,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    })
}

const get = (url, params) => {
    return axios({
        method: 'get',
        url,
        params,
        // headers: {
        //     'X-Requested-With': 'XMLHttpRequest',
        // }
    })
}

const put = (url, data) => {
    return axios({
        method: 'put',
        url,
        data: data,
        // headers: {
        //     'Content-Type': 'application/json;charset=utf-8'
        // }
    })
}

const del = (url, data) => {
    return axios({
        method: 'delete',
        url,
        data: data,
        // headers: {
        //     'Content-Type': 'application/json;charset=utf-8'
        // }
    })
}


const down = (url, data) => {
    return axios({
        method: 'post',
        url,
        data: data,
        responseType: "blob",
    })
}

export default {
    post, get, put, del, down
}